package cn.sourcespro.spring.config;

import cn.sourcespro.spring.entity.SysAuthorize;
import cn.sourcespro.spring.service.SysAuthorizeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * security
 *
 * @author zhanghaowei
 * @date 2018/7/27
 */
public class MyFilterSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    private static final Logger logger = LoggerFactory.getLogger(MyFilterSecurityMetadataSource.class);

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    private SysAuthorizeService sysAuthorizeService;

    private List<SysAuthorize> sysAuthorizeList;

    public MyFilterSecurityMetadataSource(SysAuthorizeService sysAuthorizeService) {
        this.sysAuthorizeService = sysAuthorizeService;
    }

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        FilterInvocation fi = (FilterInvocation) object;
        String url = fi.getRequestUrl();
        String httpMethod = fi.getRequest().getMethod();
        if (sysAuthorizeList == null) {
            sysAuthorizeList = new ArrayList<>();
            logger.info("==> 从数据库加载权限配置");
            sysAuthorizeList = sysAuthorizeService.findAll();
            logger.info("<== 加载权限完成：{}个", sysAuthorizeList.size());
        }
        for (SysAuthorize sysAuthorize : sysAuthorizeList) {
            String role = sysAuthorize.getRole();
            if (!StringUtils.isEmpty(role) && antPathMatcher.match(sysAuthorize.getUrl(), url)) {
                return SecurityConfig.createList(role);
            }
        }
        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        logger.info("getAllConfigAttributes()");
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        logger.info("supports(Class<?> clazz)");
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}
